package com.huawei.push.controller.service;

import com.huawei.push.android.*;
import com.huawei.push.controller.Json.ResultJson;
import com.huawei.push.controller.enity.MsgConfigEnity;
import com.huawei.push.controller.enity.MsgEnity;
import com.huawei.push.exception.HuaweiMesssagingException;
import com.huawei.push.message.AndroidConfig;
import com.huawei.push.message.Message;
import com.huawei.push.message.Notification;
import com.huawei.push.messaging.HuaweiApp;
import com.huawei.push.messaging.HuaweiCredential;
import com.huawei.push.messaging.HuaweiMessaging;
import com.huawei.push.messaging.HuaweiOption;
import com.huawei.push.model.Urgency;
import com.huawei.push.model.Visibility;
import com.huawei.push.reponse.SendResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 华为的封装的发送方法
 */
@Component
public class HuaWeiAppSendMsg {
    private static Log log = LogFactory.getLog(VivoAppSendMsg.class);
    @Resource
    private MsgConfigEnity msgConfigEnity;
    private HuaweiMessaging messaging;
    private HuaweiOption option;
    private HuaweiApp app;

    @Value("${huawei.appId}")
    private String appId;

    @Value("${huawei.appSecret}")
    private String appSecret;

    /**
     * 初始化时加载HuaweiApp， 获取accessToken
     */
    @PostConstruct
    public void init() {
        final HuaweiCredential credential = HuaweiCredential.builder()
                .setAppId(appId)
                .setAppSecret(appSecret)
                .build();

        option = HuaweiOption.builder()
                .setCredential(credential)
                .build();
        app = HuaweiApp.initializeApp(option);
        messaging = HuaweiMessaging.getInstance(app);
    }

    /**
     * 呼吸灯设置
     *
     * @return
     */
    private LightSettings getLightSettings() {
        //       呼吸灯
        return LightSettings.builder().setColor(Color.builder().setAlpha(0f).setRed(0f).setBlue(1f).setGreen(1f).build())
                //                呼吸灯点亮时间间隔，格式按照“\d+\｜\d+[sS]\｜\d+.\d{1,9}\｜\d+.\d{1,9}[sS]”
                .setLightOnDuration(msgConfigEnity.getLightOnDuration())
                //                呼吸灯熄灭时间间隔，格式按照“\d+\｜\d+[sS]\｜\d+.\d{1,9}\｜\d+.\d{1,9}[sS]
                .setLightOffDuration(msgConfigEnity.getLightOFFDuration())
                .build();
    }

    /**
     * 生成消息配置 譬如 消息缓存时间 消息标识
     *
     * @param androidNotification
     * @return
     */
    private AndroidConfig getAndroidConfig(AndroidNotification androidNotification) {
        return AndroidConfig.builder().setCollapseKey(-1)
                .setUrgency(Urgency.HIGH.getValue())
                //                消息缓存时间
                .setTtl("10000s")
                //                批量任务消息标识
                .setBiTag("YunJingBiTag")
                .setNotification(androidNotification)
                .build();
    }

    /**
     * 点击消息体 只跳转到app中不固定界面
     *
     * @param title
     * @param notifySummary
     * @param body
     * @param groupName
     * @return
     */
    public AndroidConfig setConfigWithContent(String title, String notifySummary, String body, String groupName) {
//       呼吸灯设置
        LightSettings lightSettings = getLightSettings();

        AndroidNotification androidNotification = AndroidNotification.builder()
                .setColor(msgConfigEnity.getColor())
//                使用当前手机默认铃声
                .setDefaultSound(true)
//                设置消息点击跳转app
                .setClickAction(ClickAction.builder().setType(3).build())
//                随便设置个通道ID
                .setChannelId("tempChannelId20210101")
//                通知栏名称设置
                .setNotifySummary(notifySummary)
//                1-bigbody样式 3-indexcontent样式内容
                .setStyle(1)
//                大文字效果展示
                .setBigTitle(title)
                .setBigBody(body)
//                消息展示时间
                .setAutoClear(msgConfigEnity.getAutoClear())
                .setGroup(groupName)
                .setImportance(msgConfigEnity.getImportance())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .addAllButtons(msgConfigEnity.getButton())
                .build();
        AndroidConfig androidConfig = getAndroidConfig(androidNotification);

        return androidConfig;
    }

    /**
     * 设置点击文本时会跳转到url对象中
     *
     * @param title 消息标题
     * @param notifySummary 通知栏消息
     * @param body 消息体
     * @param groupName 分组名
     * @return
     */
    public AndroidConfig setConfigWithUrl(String title, String notifySummary, String body, String groupName, String url) {
        LightSettings lightSettings = getLightSettings();
        AndroidNotification androidNotification = AndroidNotification.builder()
                .setColor(msgConfigEnity.getColor())
//                使用当前手机默认铃声
                .setDefaultSound(true)
//               消息标签，同一应用下使用同一个消息标签的消息会相互覆盖，只展示最新的一条。
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(2).setUrl(url).build())
                //               通道id不需要特别设置。
                .setChannelId("tempChannelId20210101")
                .setNotifySummary(notifySummary)
//                通知栏样式：0 - 默认样式;1 - 大文本样式;3 - Inbox样式 当style为3时，setInbox样式的内容（必选），支持最大5条内容，每条最大长度1024。
                .setStyle(1)
                .setBigTitle(title)
                .setBigBody(body)
//                消息展示时间
                .setAutoClear(msgConfigEnity.getAutoClear())
                .setGroup(groupName)
                .setImportance(msgConfigEnity.getImportance())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .addAllButtons(msgConfigEnity.getButton())
                .build();
        AndroidConfig androidConfig = getAndroidConfig(androidNotification);

        return androidConfig;
    }

    /**
     * 设置点击文本时会跳转到应用对应的界面中
     *
     * @param title
     * @param notifySummary
     * @param body
     * @param groupName
     * @return
     */
    public AndroidConfig setConfigWithActionUrl(String title, String notifySummary, String body, String groupName, String action) {
        LightSettings lightSettings = getLightSettings();
        AndroidNotification androidNotification = AndroidNotification.builder()
                .setColor(msgConfigEnity.getColor())
//                使用当前手机默认铃声
                .setDefaultSound(true)
//               消息标签，同一应用下使用同一个消息标签的消息会相互覆盖，只展示最新的一条。
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(1).setAction(action).build())
//               通道id不需要特别设置。
                .setChannelId("tempChannelId20210101")
                .setNotifySummary(notifySummary)
//                1-bigbody样式 3-indexcontent样式内容
                .setStyle(1)
                .setBigTitle(title)
                .setBigBody(body)
//                消息展示时间
                .setAutoClear(msgConfigEnity.getAutoClear())
                .setGroup(groupName)
                .setImportance(msgConfigEnity.getImportance())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .addAllButtons(msgConfigEnity.getButton())
                .build();
        AndroidConfig androidConfig = getAndroidConfig(androidNotification);

        return androidConfig;
    }


    /**
     *  发送消息
     * @param token 用户列表
     * @param title 消息标题
     * @param body 消息内容
     * @param notifySummary 消息通知栏名称
     * @return
     */
    public String SendMSg(List<String> token, String title,String body,String notifySummary,String groupName) {

        if (CollectionUtils.isEmpty(token)){
            return ResultJson.bad("用户为空！",null);
        }

        if (!StringUtils.hasLength(body)){
            return  ResultJson.bad("消息内容不能为空！",null);
        }
        //构造消息通知
        Notification notification = Notification.builder().setTitle(title)
                .setBody(body)
                .build();
        //设置消息配置
        Message message = Message.builder().setNotification(notification)
                .setAndroidConfig(setConfigWithContent(title, notifySummary, body, groupName))
                .addAllToken(token)
                .build();
        SendResponse response = null;
         try {
              //发送并获取相应信息
              response = messaging.sendMessage(message);

            return ResultJson.ok(response.getMsg(),null);
        } catch (HuaweiMesssagingException e) {
            e.printStackTrace();
            log.debug(e.getMessage(),e.getCause());
            //华为自定义异常
            return ResultJson.bad(e.getMessage(),null);

        }


    }

}
